<?php

//
// +------------------------------------------------------------------------+
// | PHP Version 5.4                                                        |
// +------------------------------------------------------------------------+
// | Copyright (c) All rights reserved.                                     |
// +------------------------------------------------------------------------+
// | 世纪车来车往(北京）网络科技有限公司 版权所有！                                  |
// | TEL:010-63732365  HOTLINE:400-6688-365  EMAIL:clcw@clcw.com.cn         |
// | $Revision: 1.0 $                                                       |
// +------------------------------------------------------------------------+
// | Author: liguohua@clcw.com.cn Blog:http://blog.sina.com.cn/saverneo     |
// +------------------------------------------------------------------------+
//
/**
 * 拍单管理
 */

namespace AuctionBack\Controller;

use AuctionCore\AuctionOrder\AuOrder;
use AuctionCore\AuctionOrder\Recheck;
use AuctionCore\AuctionOrder\Scene;
use AuctionCore\CarDealer\Dealer;
use AuctionCore\Common\PhpRedis;
use AuctionCore\Finance\Payment;
use AuctionCore\Other\Channel;
use AuctionCore\AntNest\Subscribe;
use AuctionCore\SceneActivity\SceneActivity;
use AuctionCore\System\AuctionException;
use AuctionCore\AuctionOrder\AuOrderList as AuOrderList;
use AuctionCore\CarDealer\AssetCenter;
use AuctionCore\CarResource\Car;
use AuctionCore\Account\Back\Employee;
use AuctionCore\CarOwner\Owner;
use AuctionCore\AuctionOrder\CarReturn;
use AuctionCore\Finance\Collection;
use AuctionCore\CarResource\BreachCar;
use AuctionCore\Fours\Fours;
use AuctionCore\PurchaseOrder\PurchaseOrder;
use AuctionCore\Cashier\Payment as CashierPayment;
use AuctionCore\Company\CompanyManage;
use AuctionCore\Common\AjaxPage;
use AuctionCore\CarResource\CarSource;
use AuctionBack\Logic\CarReportLogic;
use AuctionBack\Service\Thrift\ThriftAuctionService;
use Services\AuctionService\inParamsCreateEditScene;
use Services\AuctionService\inParamsCreateOrder;

class AuOrderController extends BaseController
{

    private $emp_id = 0;
    private $auctionServiceObj;

    public function __construct()
    {
        parent::__construct();
        $this->emp_id = $this->user_info['emp_id'];
        $branch_id = $this->user_info['branch_id'];
        $this->assign('branch_id', $branch_id);
        $this->auctionServiceObj = new ThriftAuctionService();
    }

    public function index()
    {
        //场次下拉
        $scene = new Scene();
        $map = array();
        if (!$this->is_hq) {
            $map['city'] = array('in', array_flip($this->bc_city));
        }
        $scenes = $scene->get_scenes($map);

        $this->assign("scenes", $scenes);
        $this->assign("order_status", C("ORDER_STATUS"));
        $this->display();
    }

    //获取拍单列表
    public function get_list()
    {
        $params = array();
        $params['order_status'] = I("get.status");
        //print_r($params);return;
        $page = I("get.p", 1);
        $size = 10;

        if ($params['order_status'] == 1) {
            $params['scene_id'] = I("get.scene_id");
        }
        $params['bidding_start_time'] = I("get.bidding_start_time");
        $params['keyword'] = I("get.keyword");
        $params['location_area'] = I('get.location_area');

        if (!$params['location_area']) {
            $params['location_area'] = !$this->is_hq ? array_flip($this->bc_city) : array();
        }

        //获取list
        $aol = new AuOrderList();
        $result = $aol->get_list($page, $size, $params);
        //print_r($result);return;
        $Page = new AjaxPage($result['total'], $size, "get_page");
        $Page->setConfig('theme', " %totalRow% %header% %nowPage%/%totalPage% 页 %first% %upPage% %prePage% %linkPage% %downPage% %nextPage% %end% %jumpform%");
        $show = $Page->show(); // 分页显示输出
        //模板赋值
        $this->assign('page', $show); // 赋值分页输出
        $this->assign('list', $result['list']);
        $this->assign("params", $params);
        $this->assign("transfer_fee", $this->transfer_fee);
        $this->assign("commision", $this->commision);
        // echo $params['order_status'].'____';return;
        if ($params['order_status'] == 1) {
            $this->display('au_order_list');
        } elseif ($params['order_status'] == 2) {
            $this->display('audit_dismissed_list');
        } else {
            $this->display('audit_pass_list');
        }

    }

    /* ------------------上拍审核----------------------- */
    /* 详细审核 */

    public function detail_audit()
    {
        $order_id = I('get.order_id');
        try {
            $order = new \AuctionCore\AuctionOrder\AuOrder($order_id);
            $order_info = $order->detail();
        } catch (AuctionException $e) {
            die($e->getMessage());
        }
        $car = new Car($order_info['car_id']);
        $car_info = $car->detail();
        //获取车辆检测报告
        $Rep = A('CarReport');
        $report = $Rep->output_report($car_info['car_id']);

        $head['order_no'] = $order_info['order_no'];
        $head['coupon'] = $order_info['coupon'];
        $head['est_elapsed_time'] = $order_info['est_elapsed_time'] / 60;
        $scene = new \AuctionCore\AuctionOrder\Scene();
        $sc = $scene->detail($order_info['scene_id']);
        $head['scene_name'] = $sc['name'];
        $head['car_no'] = $car_info['car_no'];
        $head['suggest_price'] = format_money($car_info['suggest_min_price']) . " - " . format_money($car_info['suggest_max_price']);
        $head['suggest_bid_start_price'] = format_money($car_info['suggest_bid_start_price']);
        $head['bid_start_price_show'] = format_money($order_info['bid_start_price']);
        $head['commision'] = format_money($order_info['commision']);
        $head['transfer_fee'] = format_money($order_info['transfer_fee']);
        $head['reserve_price'] = format_money($car_info['reserve_price']);
        $head['show_reserve_price'] = $order_info['show_reserve_price'];

        $head['transfer_limit'] = C('TRANSFER_LIMIT.' . $car_info['transfer_limit']);

        $head['order_id'] = $order_info['order_id'];
        $head['order_no'] = $order_info['order_no'];
        $head['status'] = $order_info['status'];
        $head['procedure'] = $car->detail('car_procedure');
        //模板赋值
        $this->assign('head', $head);
        $this->assign('report', $report);
        $this->display();
    }

    /**
     * 审核
     */
    public function audit()
    {
        //获取提交数据
        $orderId = I('request.order_id');
        $act = I('request.act') == 'pass' ? true : false ;
        $remarkReject = urldecode(I('request.remark_reject'));
        $result = $this->auctionServiceObj->auditOrder($orderId,$act,$remarkReject,$this->emp_id);
        if ($result === true) {
            $result = [
                'code' => 200,
                'msg' => '成功'
            ];
        }
        $this->helpJsonResult($result['code'], $result['msg']);
        return;

        //TODO:权限判断
        //获取拍单信息
        try {
            $order = new \AuctionCore\AuctionOrder\AuOrder($order_id);
            $detail = $order->detail();
        } catch (AuctionException $e) {
            $this->helpJsonResult($e->getCode(), $e->getMessage());
        }
        //初始化变量
        $code = '200';
        $msg = '';
        if ($act == 'pass') {
            //数据验证
            if ($detail['status'] > '3') {
                $this->helpJsonResult('512', '不能重复审核上拍');
                exit;
            }
            //时效性验证
            $scene = $order->get_scene($detail['scene_id']);
            if (time() > strtotime($scene['starttime'])) {
                $msg = $scene['status'] == '2' ? '不能上拍，该场拍卖已开始' : '不能上拍，该场拍卖已结束';
                $this->helpJsonResult('542', $msg);
                exit;
            }

            //要提前场开始时间2分钟审核
            if ((time() + 120) > strtotime($scene['starttime'])) {
                $this->helpJsonResult('555', '本场次已停止审核，请驳回此车辆重新上拍');
                exit;
            }

            //开启事务
            M()->startTrans();
            //更新车源上拍次数,流拍次数
            $cars = new \AuctionCore\CarResource\Car($detail['car_id']);
            $car_detail = $cars->detail();


            /*
            取消更新采购单中拍单信息的逻辑
            $sid = $car_detail['sid'];
            $purchaseOrderObj = new PurchaseOrder();
            $purchaseOrderData['order_id'] = $detail['order_id'];
            $purchaseOrderData['order_no'] = $detail['order_no'];

            $data = $purchaseOrderObj->viewBySid($sid);
            if (!empty($data)) {
                $updateResult = $purchaseOrderObj->updateBySid($sid, $purchaseOrderData);
                if (!$updateResult) {
                    M()->rollback();
                    $this->helpJsonResult(500, '更新采购单失败');
                }
            }*/
            //更新车源状态
            $CarSource = new CarSource($car_detail['sid']);
            $CarSourceInfo = $CarSource->getInfo();
            $res_cs = true;
            if ($CarSourceInfo['status'] == 100) {
                $csData = [];
                $csData['status'] = 200;
                $res_cs = $CarSource->update($csData);
            }

            $car_data = array();
            $car_data['car_status'] = '5';
            $car_data['au_times'] = $car_detail['au_times'] + 1;
            if ($detail['status'] == '6' && $car_detail['re_auction_type'] == '1') {
                $car_data['unsold_times'] = $car_detail['unsold_times'] - 1;
            }
            $res1 = $cars->update($car_data);
            //更新拍单表
            $data = array();
            $data['status'] = '3'; //审核通过，状态改为3 拍卖中
            $data['bid_start_time'] = date('Y-m-d H:i:s');//原来的投标开始时间，现在为审核通过时间
            $res = $order->update($data);

            if (!$res || !$res1 || !$res_cs) {
                M()->rollback();
                $this->helpJsonResult(500, '上拍审核失败');
            }
            M()->commit();
            $Sub = new Subscribe();
            $Sub->add($this->emp_id, $order_id);

            //智能出价redis更新
            $redis = new PhpRedis(0);
            //所在地
            $a = new \AuctionCore\Other\Address();
            $city_name = $a->get_name_by_code($car_detail['location_area']);

            //车系
            $cm = new \AuctionCore\CarResource\CarModel();
            $series = $cm->get_model_by_id($car_detail['series_id'], 'series');
            //合成车型
            $car_model = '[' . $city_name . '] ' . $series['name'] . ' ' . $car_detail['car_cc'] . ($car_detail['turbo'] ? 'T' : 'L') . ' ' . C('GEARBOX.' . $car_detail['gearbox']);


            $order_info = array(
                'order_id' => intval($order_id),
                'bidding_start_time' => $detail['bidding_start_time'],
                'bid_start_price' => floatval($detail['bid_start_price']),
                'order_no' => $detail['order_no'],
                'car_model' => $car_model
            );
            $arr = [
                'order_id'=>$order_id,
            ];
            $keyName = getRedisKeyByCode('REDIS_KEY','100002',$arr);
            $redis->set($keyName, json_encode($order_info));
            //$redis->set('autobidding_order_info_' . $order_id, json_encode($order_info));
            $code = '200';
            $msg = '上拍审核成功';
        } elseif ($act == 'reject') {
            //数据验证
            if ($detail['status'] == '2') {
                $this->helpJsonResult('513', '不能重复驳回上拍');
            }
            //更新拍单表
            $data = array();
            $data['status'] = '2'; //审核驳回
            $data['rank'] = '0'; //排序置0
            $data['remark_reject'] = $remark_reject;

            //开启事务
            M()->startTrans();


            //智能出价redis更新
            //2016-11-28   by:shaoshuai
            $redis = new PhpRedis(0);
            $order_info = array(
                'order_id' => intval($order_id),
                'bidding_start_time' => $detail['bidding_start_time'],
                'bid_start_price' => floatval($detail['bid_start_price'])
            );
            $redis->set('autobidding_order_info_' . $order_id, json_encode($order_info));


            //更新场次内拍单的rank
            $res1 = $order->reset_order_rank();
            //更新场次内顺序单的开拍时间
            $res2 = $order->reset_order_start_time($detail['is_timing_order']);
            $res = $order->update($data);

            if ($res && $res1 && $res2) {
                //提交事务
                M()->commit();
                $code = '200';
                $msg = '驳回上拍成功';
            } else {
                //事务回滚
                M()->rollback();
                $code = '510';
                $msg = '驳回上拍失败';
            }
        }
        //记录车辆全局跟踪日志
        $glog = array('emp_id' => $this->emp_id, 'order_id' => $order_id, 'result' => '审核上拍');
        \AuctionCore\System\GlobalLog::add($glog);
        //
        //记录操作日志
        $log = array('emp_id' => $this->emp_id, 'order_id' => $order_id, 'action' => $msg);
        \AuctionCore\System\SystemLog::add($log);

        /**
         * 记录车辆跟踪日志
         */
        $car_action_data = array(
            'action_name' => $msg,
            'emp_id' => $this->emp_id
        );
        \AuctionCore\CarResource\Car::add_car_trace_log($detail['car_id'], $car_action_data);
        /**
         * 记录拍品跟踪日志
         */
        $order_action_data = array(
            'action_name' => $msg,
            'emp_id' => $this->emp_id
        );
        \AuctionCore\AuctionOrder\AuOrder::add_order_trace_log($order_id, $order_action_data);

        if ($detail['status'] == 3) {
            /**
             * 上拍审核成功->即竞标开始
             * 记录车辆跟踪日志
             */
            $car_action_data = array(
                'action_name' => '开始投标',
                'emp_id' => 0
            );
            \AuctionCore\CarResource\Car::add_car_trace_log($detail['car_id'], $car_action_data);
            /**
             * 记录拍品跟踪日志
             */
            $order_action_data = array(
                'action_name' => '开始投标',
                'emp_id' => 0
            );
            \AuctionCore\AuctionOrder\AuOrder::add_order_trace_log($order_id, $order_action_data);
        }
        $this->helpJsonResult($code, $msg);
    }

    /**
     * 详细审核页面
     */
    public function detail()
    {
        $this->display('detail');
    }

    /* ------------------场次管理----------------------- */

    /**
     * 获取场次
     */
    public function scene()
    {
        //分公司列表
        $compony_list = $this->get_branch_company_list();
        $scene = new \AuctionCore\AuctionOrder\Scene();
        $city = $scene->get_cicy_by_branch_id();

        $componyCityList = $this->get_company_city(); //获取公司城市列表
        //$activity_list = $this->get_scene_activity_by_branch_id(); // 通过分公司编号，得到活动信息

        //compony_list = $this->get_branch_company_list();
        $this->assign('compony_city_list', $componyCityList);
        $this->assign('compony_list', $compony_list);
        //$this->assign('scene_activity_list', $activity_list);
        $this->display('scene');
    }


    /**
     *  得到公司城市列表
     *
     * @return mixed
     */
    public function get_company_city()
    {
        $arr = CompanyManage::get_company_city();
        return $arr;
    }

    /**
     * 根据分公司编号得到相应的活动信息
     *
     * @return mixed
     */
    public function get_scene_activity_by_branch_id()
    {
        $start_time = I('post.start_time', '');
        $branch_id = I('post.branch_id/d', 0);
        if (empty($start_time)) {
            $this->helpJsonResult(400, "请选择场次开始时间");
        }
        $params['start_time'] = $start_time;
        $params['branch_id'] = $branch_id;
        $result = SceneActivity::getSceneActivityByBranchId($params);
        $this->helpJsonResult(200, "", $result);
    }


    /**
     * ajax获取场次列表
     */
    public function scene_list()
    {
        $page = I("get.p", 1);
        $size = 10;
        $params = array();
        $params['car_status'] = I("get.car_status");
        $params['brand_id'] = I("get.brand_id");
        $params['series_id'] = I("get.series_id");
        $params['model_id'] = I("get.model_id");
        $params['keyword'] = I("get.keyword");
        $params['location_area'] = I('get.location_area');
        if (!$params['location_area']) {
            $params['location_area'] = !$this->is_hq ? array_flip($this->bc_city) : array();
        }
        //获取list
        $aol = new AuOrderList();
        $result = $aol->scene_list($page, $size, $params);
        $Page = new AjaxPage($result['total'], $size, "get_page");
        $Page->setConfig('theme', " %totalRow% %header% %nowPage%/%totalPage% 页 %first% %upPage% %prePage% %linkPage% %downPage% %nextPage% %end% %jumpform%");
        $show = $Page->show(); // 分页显示输出

        //模板赋值
        $this->assign('page', $show); // 赋值分页输出
        $this->assign('list', $result['list']);
        $this->assign("params", $params);
        $this->assign("transfer_fee", $this->transfer_fee);
        $this->assign("commision", $this->commision);
        $this->display('scene_list');
    }

    /**
     * (新建/编辑)场次
     */
    public function add_scene()
    {
        //从表单获取数据
        $scene_id = I('post.scene_id');
        $name = I('post.name');
        $starttime = I('post.starttime');
        $city = I('post.city');
        $status = I('post.status');
        $scene_activity = I('post.scene_activity/d');
        $branch_id = I('post.branch_id/d');

        $code = '200';
        $msg = 'SUCCESS';
        $data = array();
        $data['emp_id'] = $this->emp_id;
        if ($name) {
            $data['name'] = $name;
        } else {
            $code = '543';
            $msg = '场次名称不能为空';
        }
        if ($starttime) {
            $data['starttime'] = $starttime;
            if (strtotime($starttime) < time()) {
                $code = '422';
                $msg = '场次开始时间不能小于当前时间';
            }
        } else {
            $code = '544';
            $msg = '场次开始时间不能为空';
        }

        if ($city) {
            $data['city'] = $city;
        } else {
            $code = '544';
            $msg = '所属城市不能为空';
        }

        if ($branch_id) {
            $data['branch_id'] = $branch_id;
        } else {
            $code = '544';
            $msg = '分公司不能为空';
        }

        if ($code != 200) {
            $this->helpJsonResult($code, $msg);
            return;
        }
        $parameters = new inParamsCreateEditScene();
        $parameters->name = $name;
        $parameters->branchId = intval($branch_id);
        $parameters->starttime = strtotime($starttime);
        $parameters->city = intval($city);
        $parameters->sceneActivity = intval($scene_activity);
        $parameters->empId = intval($this->emp_id);
        $parameters->sceneId = intval($scene_id);
        $result = $this->auctionServiceObj->createEditScene($parameters);
        if ($result === true) {
            $result = [
                'code' => 200,
                'msg' => '成功'
            ];
        }
        $this->helpJsonResult($result['code'], $result['msg']);
        return;
    }


    /**
     *  通过城市编号得到场次信息
     *
     * @return mixed
     */
    public function get_scenes_by_city()
    {
        $city = I('post.city');
        $scene = new \AuctionCore\AuctionOrder\Scene();
        $map['city'] = $city;
        $scenes_data = $scene->get_scenes($map);
        $this->helpJsonResult('200', '', $scenes_data);
    }

    /**
     * 获取场次详情
     */
    function get_scene()
    {
        $scene_id = I('get.scene_id');
        $scene = new \AuctionCore\AuctionOrder\Scene();
        $detail = $scene->detail($scene_id);
        $activityInfo = $scene->getActivityBySceneId($scene_id);
        $detail['scene_activity_id'] = $activityInfo['scene_activity_id'];

        //$detail['branch_id'] = $activityInfo['branch_id'];

        /* echo "<pre>";
        print_r($activityInfo);
        echo "</pre>";*/

        $this->helpJsonResult(200, "", $detail);
        exit;
    }

    /* ------------------拍品排序----------------------- */

    /**
     * 场次拍品
     */
    public function scene_auction()
    {
        $scene_id = I('get.scene_id');
        $scenes = array(); //今日场次
        $scene = new \AuctionCore\AuctionOrder\Scene();
        $scene_detail = $scene->detail($scene_id);
        $a = new \AuctionCore\Other\Address();
        $scene_detail['city'] = $a->get_name_by_code($scene_detail['city']);
        $this->assign("scene", $scene_detail);
        $this->assign("scene_id", $scene_id);
        $this->display();
    }

    /**
     * ajax场次拍品列表
     */
    public function scene_auction_list()
    {
        $page = I("get.p", 1);
        $size = 1000;
        $params = array();
        $params['scene_id'] = I('get.scene_id');
        $params['status'] = I("get.status");
        //获取list
        $aol = new AuOrderList();
        $result = $aol->scene_auction_list($page, $size, $params);
        $Page = new AjaxPage($result['total'], $size, "get_page");
        $Page->setConfig('theme', " %totalRow% %header% %nowPage%/%totalPage% 页 %first% %upPage% %prePage% %linkPage% %downPage% %nextPage% %end% %jumpform%");
        $show = $Page->show(); // 分页显示输出
        //模板赋值
        $this->assign('page', $show); // 赋值分页输出
        $this->assign('list', $result['list']);
        $this->display();
    }

    /**
     * 编辑定时单开拍时间
     */
    public function edit_timing_order()
    {
        $order_id = I('post.order_id');
        $bidding_start_time = I('post.bidding_start_time');
        //数据验证
        if (!$order_id) {
            $code = '514';
            $msg = '拍单ID不能为空';
            $this->helpJsonResult($code, $msg);
            exit;
        }
        if (!$bidding_start_time) {
            $code = '550';
            $msg = '开拍时间不能为空';
            $this->helpJsonResult($code, $msg);
            exit;
        }

        try {
            $order = new \AuctionCore\AuctionOrder\AuOrder($order_id);
            $detail = $order->detail();

            //定时单开拍时间要在场开始时间和结束时间内
            $car = new \AuctionCore\CarResource\Car($detail['car_id']);
            $c = $car->check_bidding_start_time($detail['scene_id'], $bidding_start_time);
            if (!$c) {
                $code = '549';
                $msg = '定时单开拍时间不能早于场次开始时间且必须和场次是同一天';
                $this->helpJsonResult($code, $msg);
                exit;
            }
        } catch (\Exception $e) {
            $code = $e->getCode();
            $msg = $e->getMessage();
            $this->helpJsonResult($code, $msg);
            exit;
        }
        $data = array();
        $data['bidding_start_time'] = $bidding_start_time;
        $ret = $order->update($data);
        if ($ret) {
            $code = '200';
            $msg = '修改成功';
        } else {
            $code = '200';
            $msg = '修改失败或数据未更新';
        }
        $this->helpJsonResult($code, $msg);
        exit;
    }

    /**
     * 拍品排序
     *
     * @param int order_id1 拍单ID
     * @param int order_id2 拍单ID
     * @param int direction(up,down) 排序方向
     */
    public function ranking()
    {
        $orderModel = M("Order");
        $order_id1 = I("post.order_id1");
        $order_id2 = I("post.order_id2");
        $direction = I("post.direction");
        if ($direction == "up") {
            $order1 = $orderModel->field('rank,scene_id')->where(array('order_id' => $order_id1))->find();
            $order2 = $orderModel->field('rank')->where(array('order_id' => $order_id2))->find();
            if ($order1 && $order2) {
                $orderModel->field('rank')->where(array('order_id' => $order_id1))->save(array('rank' => $order2['rank']));
                $orderModel->field('rank')->where(array('order_id' => $order_id2))->save(array('rank' => $order1['rank']));
            }
            $json['order_rank1'] = $order2['rank'];
            $json['order_rank2'] = $order1['rank'];
        } elseif ($direction == "down") {
            $order1 = $orderModel->field('rank,scene_id')->where(array('order_id' => $order_id1))->find();
            $order2 = $orderModel->field('rank')->where(array('order_id' => $order_id2))->find();
            if ($order1 && $order2) {
                $orderModel->field('rank')->where(array('order_id' => $order_id1))->save(array('rank' => $order2['rank']));
                $orderModel->field('rank')->where(array('order_id' => $order_id2))->save(array('rank' => $order1['rank']));
            }
            $json['order_rank1'] = $order2['rank'];
            $json['order_rank2'] = $order1['rank'];
        }
        $json['order_id1'] = $order_id1;
        $json['order_id2'] = $order_id2;
        //重新计算顺序单开拍时间
        $scene = new \AuctionCore\AuctionOrder\Scene();
        $scene->re_compute_starttime($order1['scene_id']);

        echo json_encode($json);
    }

    /* ------------------车主确认----------------------- */

    /**
     * 车主确认列表
     */
    public function owner_confirm()
    {
        $this->display('owner_confirm');
    }

    /**
     * 获取车主确认分页
     */
    public function owner_confirm_list()
    {
        $page = I("get.p", 1);
        $size = 10;
        $params = array();
        $params['status'] = I("get.status");
        if ($params['status'] == '1') {
            $params['trace_start_time'] = I("get.trace_start_time", '');
            $params['trace_end_time'] = I("get.trace_end_time", '');
        } elseif ($params['status'] == '3' || $params['status'] == '4') {
            $params['confirm_start_time'] = I("get.confirm_start_time", '');
            $params['confirm_end_time'] = I("get.confirm_end_time", '');
        }
        $params['order_no'] = I("get.order_no", '');
        $params['location_area'] = I('get.location_area');
        if (!$params['location_area']) {
            $params['location_area'] = !$this->is_hq ? array_flip($this->bc_city) : array();
        }

        $params['emp_id'] = $this->emp_id;
        //检查权限
        $rules = "CheZhuQueRenChaKanSuoYou";
        $e = new Employee($this->user_info['username']);
        $auth = $e->check_auth($rules);
        $params['auth'] = $auth;

        //检查分配权限
        $fenpei_rules = "CheZhuQueRenFenPei";
        $fenpei_auth = $e->check_auth($fenpei_rules);
        $params['fenpei_auth'] = $fenpei_auth;
        //获取客服
        if ($fenpei_auth) {
            $kefu_list = Employee::get_branch_emp(C('OWNER_CONSULT_SERVER.0'));
            $this->assign('kfs', $kefu_list);
        }
        //获取list
        $aol = new AuOrderList();
        $result = $aol->owner_confirm_list($page, $size, $params);
        // var_export($result);
        $Page = new AjaxPage($result['total'], $size, "get_page");
        $Page->setConfig('theme', " %totalRow% %header% %nowPage%/%totalPage% 页 %first% %upPage% %prePage% %linkPage% %downPage% %nextPage% %end% %jumpform%");
        $show = $Page->show(); // 分页显示输出
        //模板赋值
        $this->assign('params', $params);
        $this->assign('page', $show); // 赋值分页输出
        $this->assign('list', $result['list']);
        $this->display('owner_confirm_list');
    }

    //分配客服
    public function assignServer()
    {
        $order_id = I('post.order_id/d', '');
        if (empty($order_id)) {
            $this->helpJsonResult(400, "拍单信息错误!");
        }
        $service_id = I('post.service_id/d', '');
        if (empty($service_id)) {
            $this->helpJsonResult(400, "请选择客服");
        }
        $order = new AuOrder($order_id);
        $order_detail = $order->detail();
        if (empty($order_detail)) {
            $this->helpJsonResult(404, "拍单不存在");
        }
        $data['owner_confirm_service_id'] = $service_id;
        $ok = $order->update($data);
        if (!$ok) {
            $this->helpJsonResult(500, " 分配失败,请稍后再试 ");
        }
        /**
         * 记录车辆跟踪日志
         */
        $car_action_data = array(
            'action_name' => "车主确认，跟踪分配",
            'emp_id' => $this->emp_id
        );
        \AuctionCore\CarResource\Car::add_car_trace_log($order_detail['car_id'], $car_action_data);
        /**
         * 记录拍品跟踪日志
         */
        $order_action_data = array(
            'action_name' => "车主确认，跟踪分配",
            'emp_id' => $this->emp_id
        );
        \AuctionCore\AuctionOrder\AuOrder::add_order_trace_log($order_detail['order_id'], $order_action_data);

        $this->helpJsonResult(200, "分配成功");
    }

    /**
     * 检查拍单是否已被领
     *
     * @param      $order_id
     * @param      $type
     * @param bool $return
     *
     * @return AuOrder 是否返回$order Object
     */
    public function is_order_assigned($order_id, $type, $return = false)
    {
        $order_id = $order_id ? $order_id : I('get.order_id');
        $type = $type ? $type : I('get.type');
        if (intval($order_id) < 1) {
            $this->helpJsonResult("400", "参数错误");
        }
        $col = '';
        $order = new AuOrder($order_id);
        $info = $order->detail();
        if (empty($info)) {
            $this->helpJsonResult(400, "拍单信息不存在");
        }
        $car = new Car($info['car_id']);
        $carInfo = $car->detail();
        switch ($type) {
            case 'owner_confirm':
                $col = 'owner_confirm_service_id';
                $msg = '车主确认跟踪';
                break;
            case 'dealer_confirm':
                $col = 'dealer_confirm_service_id';
                $msg = '车商确认跟踪';
                break;
            case 'unsold':
                $col = 'unsold_service_id';
                $msg = '流拍跟踪';
                break;
            case 'arbitrate':
                $col = 'arbitrate_service_id';
                $msg = '仲裁跟踪';
                break;
            case 'platform_confirm':
                $col = 'platform_confirm_service_id';
                $msg = '平台确认跟踪';
                break;
            default:
                break;
        }
        if ($info[$col] > 0 && $info[$col] != $this->emp_id) {//分配此单给客户
            $this->helpJsonResult('526', '此信息正在被其他人使用');
        }
        if ($info[$col] == '0') {//尚未分配
            //分配此单给客服
            $order->update(array($col => $this->emp_id));
            $log = array('order' => $order_id, 'emp_id' => $this->emp_id, 'action' => '系统分配拍单。' . $msg);
            \AuctionCore\System\SystemLog::add($log);
            $owner = new Owner($carInfo['owner_id']);
            $owner->update(array('next_trace_time' => '0000-00-00 00:00:00'));
        }
        if (!$return) {
            $this->helpJsonResult(200, "");
            exit;
        }
        return $order;
    }

    /**+
     * 车主确认详情
     */
    public function owner_confirm_detail()
    {
        //------获取数据
        $order_id = I('get.order_id');
        $status = I('get.status');
        //------------判断拍单是否被分配

        if ($status < 2) {
            $order = $this->is_order_assigned($order_id, 'owner_confirm', true);
        } else {
            $order = new AuOrder($order_id);
        }
        //--------获取拍单详情
        $detail = $order->owner_confirm_detail();
        $city = new \AuctionCore\Other\Address();
        $detail['reg_city'] = $city->get_name_by_code($detail['reg_city']);
        //获取车源详情
        // $car = new \AuctionCore\CarResource\Car($detail['car_id']);
        // $car_detail = $car->detail();
        //获取过户限制 渠道来源
        $car_detail = M('cars')->alias('c')->field('c.*,co.comefrom,co.comefrom_url,c.location_area')
            ->join(" LEFT JOIN " . C('DB_PREFIX') . "car_owner as co ON c.`owner_id`=co.`owner_id`")
            ->where(array('car_id' => $detail['car_id']))->find();
        $a = new \AuctionCore\Other\Address();
        $car_detail['location_area'] = $a->get_name_by_code($car_detail['location_area']);
        $this->assign('car_detail', $car_detail);
        $show_from = get_from();  //获取渠道来源信息
        $this->assign('show_from', $show_from);
        $transfer_type = C('TRANSFER_LIMIT');
        $this->assign('transfer_type', $transfer_type);
        //var_dump($car_detail);
        if ($car_detail['re_auction_type'] == '2') {//2违约流拍
            $this->assign('re_auction_type', '2');
            $this->assign('first_money', $car_detail['first_money']);
            $this->assign('success_price', $car_detail['success_price']);
        }
        //------获取跟踪日志
        $trace_log = $order->get_trace_log('owner_confirm_log');
        //------获取车主确认重拍日志
        $owner_remake_log = $order->get_owner_remake_log($order_id);

        $owner = new \AuctionCore\CarOwner\Owner($detail['owner_id']);
        $owner_detail = $owner->detail();
        $owner_info['sign_reserve_time'] = $owner_detail['sign_reserve_time'] != '0000-00-00 00:00:00' ? date("Y-m-d H:i:s", strtotime($owner_detail['sign_reserve_time'])) : $owner_detail['sign_reserve_time'];
        $owner_info['sign_service_method'] = $owner_detail['sign_service_method'];

        $store = new \AuctionCore\Other\Store();

        if ($owner_detail['sign_service_method'] == 3) {
            $map = array();
            $map['store_id'] = array('eq', $owner_detail['sign_reserve_store']);
            $store_detail = $store->detail($map);
            $owner_info['sign_service_store'] = $store_detail['store_name'];
        } elseif ($owner_detail['sign_service_method'] == 2) {
            $addr = new \AuctionCore\Other\Address();
            $province = $addr->get_name_by_code($owner_detail['sign_reserve_province']);
            $city = $addr->get_name_by_code($owner_detail['sign_reserve_city']);
            $area = $addr->get_name_by_code($owner_detail['sign_reserve_area']);
//            $location_area = $addr->get_name_by_code($owner_detail['location_area']);
            $owner_info['address'] = $province . " " . $city . " " . $area . " " . $owner_detail['sign_reserve_address'];
        }
        if ($detail['status'] >= '7' && $detail['status'] != '6' && $detail['status'] != '12'
            && $detail['owner_confirm_service_id'] > '0' && $detail['is_consult'] == 0
        ) {
            $remark_result = 1;
        } elseif ($detail['status'] >= '7' && $detail['status'] != '12'
            && $detail['owner_confirm_service_id'] > 0 && $detail['is_consult'] == 1
        ) {
            $remark_result = 4;
        }
        $remark_data['order_id'] = $order_id;
        $remark_data['result'] = $remark_result;
        $remark = $owner->read_remark($remark_data);
        $owner_info['sign_reserve_remark'] = $remark['remark'];


        $map = array();
        $map['status'] = array('eq', 0);
        $map['type'] = 3; //交付店
        if ($this->is_hq == false) {
            $map['city'] = ['in', $this->user_info['bc_code']];
        }
        $stores = $store->get_stores($map);

        //打款帐号
        $fours = new Fours();
        $fours_detail = $fours->get_fours_info(['channel_id' => $car_detail['comefrom']]);
        $fours_bank_account = $fours->get_bank_account_list_by_fid($fours_detail['fid']);
        $fours_bank_account_total = count($fours_bank_account);
        $this->assign('fours_bank_account', $fours_bank_account);
        $this->assign('fours_bank_account_total', $fours_bank_account_total);
        //-------模板赋值
        $this->assign('stores', $stores);
        $this->assign('trace_log', $trace_log);
        $this->assign('detail', $detail);
        $this->assign('status', $status);
        $this->assign('owner_info', $owner_info);
        $this->assign('owner_remake_log', $owner_remake_log);
        $this->display('owner_confirm_detail');
    }

    /**
     * 车主同意卖车
     */
    public function owner_agree()
    {
        //TODO:权限验证
        //获取外部数据
        $order_id = I('post.order_id');
        $owner_id = I('post.owner_id');
        $reserve_time = I('post.reserve_time');
        $reserve_time = transform_date($reserve_time, 2);
        $service_method = I('post.service_method');
        $reserve_province = I('post.reserve_province');
        $reserve_city = I('post.reserve_city');
        $reserve_area = I('post.reserve_area');
        $reserve_store = I('post.reserve_store/d', 0);
        $reserve_address = I('post.reserve_address');
        $reserve_remark = I('post.reserve_remark');
        $account_id = I('post.account_id');
        $bank_name = I('post.bank_name'); //银行名称
        $card_no = I('post.card_no'); //银行卡号
        $account_name = I('post.account_name');
        //数据验证
        if (!$order_id) {
            $this->helpJsonResult(400, '拍单ID不能为空');
        }
        $order = new AuOrder($order_id);
        $detail = $order->detail();
        //检查前置状态
        if ($detail['status'] != 5) {
            $this->helpJsonResult(500, "拍单状态异常,请联系管理员");
        }
        if (!$owner_id) {
            $this->helpJsonResult(400, '车主ID不能为空');
        }

        if (!$reserve_time) {
            $this->helpJsonResult(400, '预约时间不能为空');
        }
        if (!$service_method) {
            $this->helpJsonResult(400, '服务方式不能为空');
        }
        if ($service_method == 2) {
            if (!$reserve_province) {
                $this->helpJsonResult(400, '预约省份不能为空');
            }
            if (!$reserve_city) {
                $this->helpJsonResult(400, '预约城市不能为空');
            }
            if (!$reserve_area) {
                $this->helpJsonResult(400, '预约地区不能为空');
            }
            if (!$reserve_address) {
                $this->helpJsonResult(400, '预约详细地址不能为空');
            }
        } elseif ($service_method == 3) {
            if ($reserve_store < 1) {
                $this->helpJsonResult(400, '请选择预约门店');
            }
        } else {
            $this->helpJsonResult(400, '请选择正确的服务方式');
        }
        //找不到车商 建议重拍
        if ($detail['bidding_best_price'] == 0 && $detail['bid_best_price'] == 0) {
            $this->helpJsonResult(500, '此车辆无车商出价建议重拍！');
        }
        if ($detail['bidding_best_price'] > $detail['bid_best_price']) {
            $success_price = $detail['bidding_best_price'];
            $success_dealer_id = $detail['bidding_best_dealer_id'];
        } else {
            $success_price = $detail['bid_best_price'];
            $success_dealer_id = $detail['bid_best_dealer_id'];
        }
        //$success_price = $detail['bidding_best_price'] > $detail['bid_best_price'] ? $detail['bidding_best_price'] : $detail['bid_best_price'];
        $car = new \AuctionCore\CarResource\Car($detail['car_id']);
        $car_detail = $car->detail();

        $purchaseOrderArr = [
            'order_id' => $order_id,
            'order_no' => $detail['order_no'],
            'car_id' => $detail['car_id'],
            'sid' => $car_detail['sid'],
            'amount' => $success_price,
            'emp_id' => $this->emp_id,
            'type' => $car_detail['is_self_receive'] ? '2' : '1', //判断是否自收车
            'status' => '1',
            'createtime' => date('Y-m-d H:i:s', time()),
        ];

        //启动事务
        M()->startTrans();
        //更新拍单状态，记录成交价格
        $data = array();
        if ($car_detail['re_auction_type'] == '2') { //2违约流拍
            if ($car_detail['car_source'] == 1) { //4s店车源
                if ($car_detail['first_money'] > 0) {
                    $data['first_pay_status'] = '1';
                }
            } else { //个人车源
                if ($car_detail['three_in_one'] == '1') { //三证合一
                    if ($car_detail['first_money'] > 0) {
                        $data['first_pay_status'] = '1';
                    }
                } else { //三证不合一
                    $data['first_pay_status'] = '1'; //不用付首款 ，为跳过流程而标识为付款
                }
            }
            $data['success_price'] = $success_price;
//            $data['commision'] = get_commision($success_price, $starttime);
            $data['success_dealer_id'] = $success_dealer_id;
            $data['status'] = '8'; //8 待付首款
            $res = $order->update($data);
            if (!$res) {
                $this->helpJsonResult(500, '操作失败，数据未更新');
            }


            $this->record_log($order_id, $detail['car_id'], $owner_id, "车主确认，成交");
            $this->helpJsonResult(200, '操作成功');
        } else { //第一次拍
            //获取检测费
//            $check_fee_conf = \AuctionCore\System\SystemConf::getConfByName('CAR_CHECK_FEE');
            //更新拍单
            if ($car_detail['car_source'] == 1) { //4S店车源无需签约,付全款
                $data['status'] = 8;
                $data['return_check_status'] = 1;
                $data['first_money'] = $success_price;
//                $data['first_money'] = $success_price - $check_fee_conf['value'];
            } else {
                $data['status'] = 7; //已确认
                $data['return_check_status'] = 3;//待复检
            }
            $data['success_price'] = $success_price;
//            $data['commision'] = get_commision($success_price, $starttime);
            $data['success_dealer_id'] = $success_dealer_id;
            $res = $order->update($data);
            //更新车主表，填写预约信息
            $owner = new Owner($owner_id);
            $res1 = $owner->update([
                'sign_reserve_time' => $reserve_time,
                'sign_service_method' => $service_method,
                'sign_reserve_province' => $reserve_province,
                'sign_reserve_city' => $reserve_city,
                'sign_reserve_area' => $reserve_area,
                'sign_reserve_address' => $reserve_address,
                'sign_reserve_store' => $reserve_store,
                'sign_next_trace_time' => $reserve_time
            ]);
            //记录下次跟踪日志
            $res2 = $owner->confirm_trace_log([
                'order_id' => $order_id,
                'service_id' => $this->emp_id,
                'reserve_time' => $reserve_time,
                'service_method' => $service_method,
                'province' => $reserve_province,
                'city' => $reserve_city,
                'area' => $reserve_area,
                'address' => $reserve_address,
                'next_trace_time' => $reserve_time,
                'remark' => $reserve_remark,
                'result' => 1
            ]);
            $car_data = [];
            $car_data['success_price'] = $success_price;
            if ($car_detail['car_source'] == 1) { //4s店车源改为待付首款
                //4s店车源添加检测费
//                $car_data['check_fee'] = $check_fee_conf['value'];
                $car_data['pay_status'] = 1;
            }
            //更新车源成交价格
            $res3 = $car->update($car_data);

            $res5 = true;
            $res6 = true;

            //TODO 生成付款单
            $paymentData['bank_name'] = $bank_name;
            $paymentData['card_no'] = $card_no;
            $paymentData['account_name'] = $account_name;
            $carReport = new CarReportLogic($detail['car_id']);
            $branchId = $carReport->getBranchId();
            $paymentData['branch_id'] = $branchId;

            //
            if ($car_detail['car_source'] == 1) {  //4S店车源添加付款和回车信息,并生成采购单
                $bank_account = json_encode(['bank_name' => $bank_name, 'card_no' => $card_no, 'account_name' => $account_name], JSON_UNESCAPED_UNICODE);
                $res4 = Payment::create($car_detail['car_id'], $order_id, 1, $account_id, $bank_account);
                if (!$res4) {
                    M()->rollback();
                    $this->helpJsonResult(500, "添加付款信息失败");
                }
                $res4 = CarReturn::create([
                    'order_id' => $order_id,
                    'sid' => $car_detail['sid'],
                    'car_id' => $car_detail['car_id']
                ]);
                if (!$res4) {
                    M()->rollback();
                    $this->helpJsonResult(500, "添加回车信息失败");
                }
                $res5 = $this->addPurchaseOrder($purchaseOrderArr); //添加采购单
                if (!$res5) {
                    M()->rollback();
                    $this->helpJsonResult(500, "添加采购单信息失败");
                }
                $paymentData['amount'] = $success_price; //4s 店全款
                $paymentData['pay_type'] = 1;
                $res6 = $this->generatorPayment($paymentData);//添加付款单

                $res7 = $this->addPaymentRelation($res5, $res6, $paymentData['pay_type']);

                if (!$res7) {
                    M()->rollback();
                    $this->helpJsonResult(500, "生成付款单关系数据失败");
                }
            } else { //个人车源，在签约时生成采购单
                /*$res6 = true;
                $res7 = true;
                if ($car_detail['three_in_one'] == 1) { //如果三证合一
                    $paymentData['pay_type'] = 2;
                    $paymentData['amount'] = $success_price * 0.5; //个人车源，三证合一付 50%
                    $res6 = $this->generatorPayment($paymentData);

                    $res7 = $this->addPaymentRelation($res5, $res6, $paymentData['pay_type']);
                }
                if (!$res6) {
                    M()->rollback();
                    $this->helpJsonResult(500, "生成付款单失败");
                }
                if (!$res7) {
                    M()->rollback();
                    $this->helpJsonResult(500, "生成付款单关系数据失败");
                }*/

                $res4 = Recheck::create([
                    'order_id' => $order_id,
                    'sid' => $car_detail['sid'],
                    'car_id' => $car_detail['car_id']
                ]);
                if (!$res4) {
                    M()->rollback();
                    $this->helpJsonResult(500, "添加复检信息失败");
                }
            }
            //过户费
            if ($detail['transfer_type'] == 1)
                $transfer_fee = 0; //车商自过 没有过户费
            else
                $transfer_fee = $detail['transfer_fee'];
            //场次活动
            $res_activity = Scene::is_scene_activity($detail['scene_id']);
            if (!empty($res_activity)) {
                //根据场次活动减免规则id找到减免规则
                foreach ($res_activity as $k => $v) {
                    if ($v['rules_type'] == 2) { //如果减免规则的rules_type == 2 说明是阶梯立减 去activity_rules表中找到相应的详细规则
                        $activity_reduction = Scene::get_activity_rules_price($v['scene_activity_id'], $success_price);
                    } else if ($v['rules_type'] == 1) { //如果减免规则rules_type == 1 说明是活动统一立减,取出scene_activity['amount'] 即可
                        $activity_reduction = $v['amount'];
                    }
                }
            } else {
                $activity_reduction = 0; //判断如果没有活动减免价格 则设置scene_activity_amount的值为0;
            }

            $orderFee = [
                'success_price' => $success_price,
                'commision' => $detail['commision'],
                'transfer_fee' => $transfer_fee,
                'final_price' => $success_price - $activity_reduction + $detail['commision'] + $transfer_fee,
                'activity_reduction' => $activity_reduction
            ];
            $res_fee = $order->addOrderFee($orderFee);
            //更新车源状态
            $CarSource = new CarSource($car_detail['sid']);
            $CarSourceInfo = $CarSource->getInfo();
            $res_cs = true;
            if ($CarSourceInfo['status'] < 400 || $CarSourceInfo['status'] == 500) {
                $csData = [];
                $csData['order_id'] = $order_id;
                $csData['status'] = '400';
                $res_cs = $CarSource->update($csData);
            }
            if (!$res || !$res1 || !$res2 || $res3 === false || !$res5 || !$res6 || !$res_fee || !$res_cs) {
                M()->rollback();
                $this->helpJsonResult(500, '确认失败或已确认,数据未更新。');
            }
            M()->commit();
            //记录车辆全局跟踪日志
            \AuctionCore\System\GlobalLog::add([
                'emp_id' => $this->emp_id,
                'order_id' => $order_id,
                'car_id' => $detail['car_id'],
                'owner_id' => $owner_id,
                'result' => '确认成交'
            ]);
            //发放抽奖卡券
            $Raffle = new \AuctionCore\Other\Raffle();
            $is_raffle = $Raffle->order_binding_card($order_id, 1);
            if ($is_raffle['is_bool'] > 0) {
                $raffle_log = array('emp_id' => $this->emp_id, 'order_id' => $order_id, 'lottery_id' => $is_raffle['cid']);
                $Raffle::grant_lottery_log($raffle_log);
            }

            //自收车辆不发卡券
            if ($car_detail['is_self_receive'] != 1) {
                //发放抽奖卡券
                $Raffle = new \AuctionCore\Other\Raffle();
                $is_raffle = $Raffle->order_binding_card($order_id, 1);
                if ($is_raffle['is_bool'] > 0) {
                    $raffle_log = array('emp_id' => $this->emp_id, 'order_id' => $order_id, 'lottery_id' => $is_raffle['cid']);
                    $Raffle::grant_lottery_log($raffle_log);
                }

                //发放抽代金券卡券
                $is_coupon = $Raffle->order_binding_card($order_id, 2);
                if ($is_coupon['is_bool'] > 0) {
                    $coupon_log = array('emp_id' => $this->emp_id, 'order_id' => $order_id, 'lottery_id' => $is_coupon['cid']);
                    $Raffle::grant_lottery_log($coupon_log);
                }
            }

            $this->record_log($order_id, $detail['car_id'], $owner_id, "车主确认，成交");
            $this->helpJsonResult(200, "操作成功");
        }
    }

    /**
     * 添加采购单
     *
     * @param $data 采购单数据
     * @return mixed 返回添加结果
     */
    public function addPurchaseOrder($data)
    {
        $obj = new PurchaseOrder();
        $purchaseOrderType = $data['type'];
        $data['purchase_order_nu'] = $obj->generatePurchaseOrderNu($purchaseOrderType);
        return $obj->add($data);
    }


    /**
     *  生成付款单
     *
     * @param $paymentData 付款单数据
     * @return mixed
     */
    public function generatorPayment($paymentData)
    {
        $paymentData['pay_way'] = 1;// 现金
        $paymentData['create_time'] = date('Y-m-d H:i:s');//创建时间
        $result = CashierPayment::add($paymentData);
        return $result;
    }

    /**
     * 添加采购单付款关系数据
     *
     * @param int $purchaseOrderId 采购单编号
     * @param int $paymentId 付款单编号
     * @param int $paymentType 付款类型
     * @return mixed
     */
    public function addPaymentRelation($purchaseOrderId, $paymentId, $paymentType)
    {
        $purchaseOrder = new PurchaseOrder();
        return $purchaseOrder->addPaymentAndPurchaseOrderRelation($purchaseOrderId, $paymentId, $paymentType);
    }

    //磋商
    public function consultation()
    {
        //获取外部数据
        $order_id = I('post.order_id/d', 0);
        $owner_id = I('post.owner_id/d', 0);
        $reserve_remark = I('post.reserve_remark');
        //数据验证
        if (!$order_id) {
            $this->helpJsonResult(500, "拍单ID不能为空");
        }

        $order = new AuOrder($order_id);
        $detail = $order->detail();
        if (empty($detail)) {
            $this->helpJsonResult(500, "未找到拍单信息");
        }
        //找不到车商 建议重拍
        if ($detail['bidding_best_price'] == 0 && $detail['bid_best_price'] == 0) {
            $this->helpJsonResult(500, '此车辆无车商出价建议重拍！');
        }

        if ($detail['bidding_best_price'] > $detail['bid_best_price']) {
            $success_price = $detail['bidding_best_price'];
            $success_dealer_id = $detail['bidding_best_dealer_id'];
        } else {
            $success_price = $detail['bid_best_price'];
            $success_dealer_id = $detail['bid_best_dealer_id'];
        }

        if (!$owner_id) {
            $this->helpJsonResult(500, "车主ID不能为空");
        }

        //启动事务
        M()->startTrans();
        //更新拍单状态，记录成交价格
        $data = array();
        $data['is_consult'] = 1;
        $data['success_price'] = $success_price;
        $data['success_dealer_id'] = $success_dealer_id;
        $res = $order->update($data);

        //记录跟踪日志
        $data = array();
        $data['order_id'] = $order_id;
        $data['owner_id'] = $owner_id;
        $data['service_id'] = $this->emp_id;
        $data['remark'] = $reserve_remark;
        $data['result'] = 4; //磋商
        $owner = new Owner($owner_id);

        $res1 = \AuctionCore\AuctionOrder\Consult::add_consult($order_id, $detail['car_id'], $owner_id, $success_dealer_id);
        try {
            $res2 = $owner->confirm_trace_log($data);
        } catch (AuctionException $e) {
            $res2 = false;
            $this->helpJsonResult($e->getCode(), $e->getMessage());
        }
        if (!$res || !$res1 || !$res2) {
            M()->rollback();
            $this->helpJsonResult(500, '确认失败或已确认,数据未更新');
        }
        M()->commit();

        //记录车辆全局跟踪日志
        \AuctionCore\System\GlobalLog::add([
            'emp_id' => $this->emp_id,
            'order_id' => $order_id,
            'car_id' => $detail['car_id'],
            'owner_id' => $owner_id,
            'result' => '车主确认,磋商'
        ]);

        /**
         * 记录车辆、拍品、员工操作日志
         */
        $this->record_log($order_id, $detail['car_id'], $owner_id, "车主确认，磋商");

        //输出json格式处理结果
        $this->helpJsonResult(200, "操作成功");
    }


    /**
     * 重拍  2016.04.14
     */
    function rephotograph()
    {
        //获取外部数据
        $order_id = I('post.order_id');
        $owner_id = I('post.owner_id');
        $reserve_price = I('post.reserve_price');
        $last_transfer_limit = I('post.last_transfer_limit');
        $transfer_limit = I('post.transfer_limit');
        $remark_fail = urldecode(I('post.remark'));
        //数据验证
        if (!$order_id) {
            $this->helpJsonResult(400, "拍单ID不能为空");
        }
        $order = new AuOrder($order_id);
        $detail = $order->detail();
        if (empty($detail)) {
            $this->helpJsonResult(400, "未找到拍单信息");
        }
        //检查前置状态
        if ($detail['status'] != 5) {
            $this->helpJsonResult(400, "拍单状态异常,请联系管理员");
        }
        if (!$owner_id) {
            $this->helpJsonResult(400, "车主ID不能为空");
        }
        if (!$reserve_price) {
            $this->helpJsonResult(400, "保留价不能为空");
        }
        if (!is_numeric($reserve_price)) {
            $this->helpJsonResult(400, "保留价输入错误");
        }

        $car = new Car($detail['car_id']);
        $car_info = $car->detail();
        /**
         * $post_date = strtotime($car_info['posttime']);
         * $now_date = time();
         * if (($now_date - $post_date) > 60 * 60 * 24 * 4) {
         * $this->helpJsonResult('518', '报告已失效，请重新上传报告');
         * }
         */
        //开启事务
        M()->startTrans();
        //拍单状态失败,失败类型为车主要求重拍，记录备注
        $res = $order->update(array(
            'status' => 12,
            'fail_type' => 1,
            'remark_fail' => $remark_fail
        ));

        //更改车源状态为7（待重拍）
        //car_status 7 待重拍,re_auction_type 1 未过保留价重拍 2车商违约重拍 3磋商失败96小时内可重拍
        $car_data = array();
        $car_data['re_auction_reason'] = $remark_fail;
        $car_data['transfer_limit'] = $transfer_limit;
        $car_data['car_status'] = '7';
        $car_data['re_auction_type'] = 1;
        $car_data['is_self_receive'] = 0;

        //保留价更改
        if ($car_info['reserve_price'] != $reserve_price) {
            $car_data['reserve_price'] = $reserve_price;
            //记录修改历史
            $reserve_price_history = json_decode($car_info['reserve_price_history']);
            array_push($reserve_price_history, array(
                'price' => $reserve_price,
                'name' => $this->user_info['real_name'],
                'id' => $this->user_info['emp_id'],
                'time' => date("Y-m-d H:i:s")
            ));
            $car_data['reserve_price_history'] = json_encode($reserve_price_history, JSON_UNESCAPED_UNICODE);
        }
        $res1 = $car->update($car_data);

        //插入跟踪日志
        $owner = new Owner($owner_id);
        $res2 = $owner->confirm_trace_log([
            'order_id' => $order_id,
            'owner_id' => $owner_id,
            'service_id' => $this->emp_id,
            'remark' => trim($remark_fail),
            'result' => 5,
        ]);

        //更新车源状态
        $CarSource = new CarSource($car_info['sid']);
        $CarSourceInfo = $CarSource->getInfo();
        $res_cs = true;
        if ($CarSourceInfo['status'] < 400) {
            $csData = [];
            $csData['status'] = '100';
            $res_cs = $CarSource->update($csData);
        }

        if (!$res || !$res1 || !$res2 || !$res_cs) {
            M()->rollback();
            $this->helpJsonResult(500, "操作失败或数据已更新未改变");
        }
        //提交事务
        M()->commit();
        //解冻车商保证金
        AssetCenter::free_all($order_id);
        /**
         * 记录车主确认的拍单重拍记录
         */
        $owner_remake_log = array(
            'emp_id' => $this->emp_id,
            'owner_id' => $owner_id,
            'car_id' => $detail['car_id'],
            'order_id' => $order_id,
            'reserve_price' => $reserve_price,
            'last_transfer_limit' => $last_transfer_limit,
            'transfer_limit' => $transfer_limit,
            'remark' => $remark_fail
        );
        \AuctionCore\AuctionOrder\AuOrder::add_owner_remake_log($owner_remake_log);

        //记录车辆全局跟踪日志
        $log = array('emp_id' => $this->emp_id, 'order_id' => $order_id, 'car_id' => $detail['car_id'], 'owner_id' => $owner_id, 'result' => '车辆重拍');
        \AuctionCore\System\GlobalLog::add($log);

        /**
         * 记录车辆、拍品、员工操作日志
         */
        $this->record_log($order_id, $detail['car_id'], $owner_id, "车主确认，重拍");

        $this->helpJsonResult(200, "操作成功");
    }

    /**
     * 种种原因，车主暂时无法确认，需要后续跟踪
     */
    public function owner_continue_trace()
    {
        //TODO:权限验证
        //获取外部数据
        $order_id = I('post.order_id');
        $owner_id = I('post.owner_id');
        $next_trace_time = I('post.next_trace_time');
        //$result = I('post.result');
        $next_trace_remark = I('post.next_trace_remark');
        //数据验证
        if (!$order_id) {
            $this->helpJsonResult(400, "拍单ID不能为空");
        }
        $order = new AuOrder($order_id);
        $detail = $order->detail();
        if (empty($detail)) {
            $this->helpJsonResult(400, "未找到拍单信息");
        }
        //检查前置状态
        if ($detail['status'] != 5) {
            $this->helpJsonResult(500, "拍单已处理过");
        }
        if (!$owner_id) {
            $this->helpJsonResult(400, "车主ID不能为空");
        }
        if (!$next_trace_time) {
            $this->helpJsonResult(400, "下次跟踪时间不能为空");
        }
        //插入下次跟踪记录
        $data = array();
        $data['order_id'] = $order_id;
        $data['service_id'] = $this->emp_id;
        $data['next_trace_time'] = $next_trace_time;
        $data['remark'] = urldecode($next_trace_remark);
        $data['result'] = 2;
        $owner = new Owner($owner_id);
        $res = $owner->confirm_trace_log($data);
        if (!$res) {
            $this->helpJsonResult("跟踪记录失败,请联系管理员");
        }

        $owner = new \AuctionCore\CarOwner\Owner($owner_id);
        $res1 = $owner->update(array('next_trace_time' => $next_trace_time));
        if (!$res1) {
            $this->helpJsonResult(400, "更新数据失败,请联系管理员");
        }
        /**
         * 记录车辆、拍品、员工操作日志
         */
        $this->record_log($order_id, $detail['car_id'], $owner_id, "车主确认，继续跟踪");
        $this->helpJsonResult(200, "操作成功");
    }

    /**
     * 车主不同意卖车
     */
    public function owner_disagree()
    {
        //TODO:权限验证
        //获取外部数据
        $order_id = I('post.order_id');
        $owner_id = I('post.owner_id');
        $remark_fail = urldecode(I('post.remark'));
        //数据验证
        if (!$order_id) {
            $this->helpJsonResult(400, '拍单ID不能为空');
        }
        $order = new AuOrder($order_id);
        $detail = $order->detail();
        if (empty($detail)) {
            $this->helpJsonResult(400, "未找到拍单信息");
        }
        if ($detail['status'] != 5) {
            $this->helpJsonResult(500, "拍单状态异常,请联系管理员");
        }
        if (!$owner_id) {
            $this->helpJsonResult(400, "车主ID不能为空");
        }
        if (!$remark_fail) {
            $this->helpJsonResult(400, '车主不卖的原因不能为空');
        }
        //开启事务
        M()->startTrans();

        //插入跟踪记录
        $fail_log = array();
        $fail_log['order_id'] = $order_id;
        $fail_log['service_id'] = $this->emp_id;
        $fail_log['remark'] = urldecode($remark_fail);
        $fail_log['result'] = 3;

        //更新车主
        $owner = new \AuctionCore\CarOwner\Owner($owner_id);
        $log_res = $owner->confirm_trace_log($fail_log);
        if (!$log_res) {
            M()->rollback();
            $this->helpJsonResult(500, "跟踪记录失败,请联系管理员");
        }

        $data = array();
        $data['business_status'] = '9'; //9预约签约失败
        $res = $owner->update($data);
        //更新拍单表数据
        $res1 = $order->update(array('status' => '12', 'fail_type' => '2', 'remark_fail' => $remark_fail)); //12 拍单失败
        //更改车源状态为8（交易失败）
        $car = new \AuctionCore\CarResource\Car($detail['car_id']);
        $res2 = $car->update(array('car_status' => '8')); //8 交易失败

        //更新车源状态
        $car_info = $car->detail();
        $CarSource = new CarSource($car_info['sid']);
        $csData = [];
        $csData['status'] = '600';
        $res_cs = $CarSource->update($csData);


        //解冻车商保证金
        AssetCenter::free_all($order_id);
        if (!$res || !$res1 || !$res2) {
            M()->rollback();
            $this->helpJsonResult(500, "操作失败或数据已更新未改变");
        }

        //提交事务
        M()->commit();
        //记录车辆全局跟踪日志
        $log = array('emp_id' => $this->emp_id, 'order_id' => $order_id, 'car_id' => $detail['car_id'], 'owner_id' => $owner_id, 'result' => '确认成交');
        \AuctionCore\System\GlobalLog::add($log);
        /**
         * 记录车辆、拍品、员工操作日志
         */
        $this->record_log($order_id, $detail['car_id'], $owner_id, "车主确认，不卖");
        //输出json格式处理结果
        $this->helpJsonResult(200, "SUCCESS");
    }

    /**
     * 车主确认失败重拍
     */
    function re_auction()
    {
        //获取外部数据
        $order_id = I('post.order_id');
        $owner_id = I('post.owner_id');
        $reserve_price = I('post.reserve_price');
        $remark_fail = urldecode(I('post.remark'));
        $last_transfer_limit = I('post.last_transfer_limit');
        $transfer_limit = I('post.transfer_limit');
        //数据验证
        if (!$order_id) {
            $this->helpJsonResult(400, "拍单ID不能为空");
        }
        //验证拍单信息
        $order = new AuOrder($order_id);
        $detail = $order->detail();
        if (empty($detail)) {
            $this->helpJsonResult(400, "未找到拍单信息");
        }

        if (!$owner_id) {
            $this->helpJsonResult(400, "车主ID不能为空");
        }
        if (!$reserve_price) {
            $this->helpJsonResult(400, "保留价不能为空");
        }
        if (!is_numeric($reserve_price)) {
            $this->helpJsonResult(400, "保留价输入错误");
        }

        $car = new Car($detail['car_id']);
        $car_detail = $car->detail();
        if ($car_detail['is_valid'] == 0) {
            $this->helpJsonResult(500, "车辆检测报告已失效");
        }
        if ($car_detail['car_status'] != 8) {
            $this->helpJsonResult('519', '车辆已重拍');
        }

//        $post_date = strtotime($car_detail['posttime']);
//        $now_date = time();
//        if (($now_date - $post_date) > 60 * 60 * 24 * 4) {
//            $this->helpJsonResult('518', '报告已失效，请重新上传报告');
//        }

        $carData = array();
        $orderData = array();
        $carData['transfer_limit'] = $transfer_limit;
        $orderData['remark_fail'] = '车辆报告有效期内重拍';
        $carData['car_status'] = '7';
        $carData['re_auction_type'] = 3;
        $carData['is_self_receive'] = 0;

        //保留价更改
        if ($car_detail['reserve_price'] != $reserve_price) {
            $carData['reserve_price'] = $reserve_price;
            //记录修改历史
            $reserve_price_history = json_decode($car_detail['reserve_price_history']);
            array_push($reserve_price_history, array(
                'price' => $reserve_price,
                'name' => $this->user_info['real_name'],
                'id' => $this->user_info['emp_id'],
                'time' => date("Y-m-d H:i:s")
            ));
            $carData['reserve_price_history'] = json_encode($reserve_price_history, JSON_UNESCAPED_UNICODE);
        }
        //开启事务
        M()->startTrans();
        $res = $order->update($orderData);
        $res1 = $car->update($carData);
        $data = array();
        $data['order_id'] = $order_id;
        $data['owner_id'] = $owner_id;
        $data['service_id'] = $this->emp_id;
        $data['remark'] = urldecode($remark_fail);
        $data['result'] = '5'; //重拍
        $owner = new Owner($owner_id);
        $res2 = $owner->confirm_trace_log($data);
        if (!$res || !$res1 || !$res2) {
            M()->rollback();
            $this->helpJsonResult(500, "操作失败或数据已更新未改变");
        }
        //提交事务
        M()->commit();
        //更新车源状态
        $CarSource = new CarSource($car_detail['sid']);
        $CarSourceInfo = $CarSource->getInfo();
        if ($CarSourceInfo['status'] == 600) {
            $csData = [];
            $csData['status'] = 100;
            $res_cs = $CarSource->update($csData);
        }
        //记录车辆全局跟踪日志
        \AuctionCore\System\GlobalLog::add([
                'emp_id' => $this->emp_id,
                'order_id' => $order_id,
                'car_id' => $detail['car_id'],
                'owner_id' => $owner_id,
                'result' => '车辆重拍']
        );

        //记录车辆跟踪日志
        Car::add_car_trace_log($detail['car_id'], [
            'action_name' => "车主确认失败，重拍",
            'emp_id' => $this->emp_id
        ]);
        /**
         * 记录拍品跟踪日志
         * 磋商失败，重拍时不记录拍单日志
         */
        if ($detail['status'] != 12 && $detail['fail_type'] != 6) {
            \AuctionCore\AuctionOrder\AuOrder::add_order_trace_log($order_id, [
                'action_name' => "拍单失败",
                'emp_id' => $this->emp_id
            ]);
        }
        //记录车主确认的拍单重拍记录
        AuOrder::add_owner_remake_log([
            'emp_id' => $this->emp_id,
            'owner_id' => $owner_id,
            'car_id' => $detail['car_id'],
            'order_id' => $order_id,
            'reserve_price' => $reserve_price,
            'last_transfer_limit' => $last_transfer_limit,
            'transfer_limit' => $transfer_limit,
            'remark' => $remark_fail
        ]);
        //记录员工操作日志
        $log = array();
        \AuctionCore\System\SystemLog::add([
            'emp_id' => $this->emp_id,
            'order_id' => $order_id,
            'car_id' => $detail['car_id'],
            'owner_id' => $owner_id,
            'action' => '重拍车源'
        ]);
        //输出json格式处理结果
        $this->helpJsonResult(200, "操作成功");
    }

    /**
     * 流拍车辆，车主确认卖车详情
     */
    public function re_auction_detail()
    {
        //获取数据
        $order_id = I('post.order_id');
        $order = new AuOrder($order_id);
        //获取详情
        $detail = $order->owner_confirm_detail();
        if ($detail['is_valid'] == 0) {
            $this->helpJsonResult(500, "车辆报告已失效");
        }
        $reserve_price = $detail['reserve_price'];
        if ($detail['status'] == 12 && $detail['fail_type'] == 6) {

            if ($detail['car_status'] != 8) {
                $this->helpJsonResult('519', '车辆已重拍');
            }
//            $post_date = strtotime($detail['posttime']);
//            $now_date = time();
//            if (($now_date - $post_date) > 60 * 60 * 24 * 4) {
//                $this->helpJsonResult('518', '报告已失效，请重新上传报告');
//            }
        }
        $result = [
            'transfer_limit' => $detail['transfer_limit'],
            'reserve_price' => $reserve_price
        ];
        $this->helpJsonResult(200, 'success', $result);
    }



    /* --------------平台确认 starting---------------- */

    /**
     * 平台确认
     */
    public function platform_confirm()
    {
        $this->display();
    }

    /**
     * 平台确认列表
     */
    public function platform_confirm_list()
    {
        $page = I("get.p", 1);
        $size = 10;
        $params = array();
        $params['status'] = I("get.status");
        if ($params['status'] == '1') {
            $params['trace_start_time'] = I("get.trace_start_time", '');
            $params['trace_end_time'] = I("get.trace_end_time", '');
        } elseif ($params['status'] == '3' || $params['status'] == '4') {
            $params['confirm_start_time'] = I("get.confirm_start_time", '');
            $params['confirm_end_time'] = I("get.confirm_end_time", '');
        }
        $params['order_no'] = I("get.order_no", '');
        $params['location_area'] = I('get.location_area');
        if (!$params['location_area']) {
            $params['location_area'] = !$this->is_hq ? array_flip($this->bc_city) : array();
        }
        $params['emp_id'] = $this->emp_id;
        //检查权限
        $rules = "PingTaiQueRenChaKanSuoYou";
        $e = new Employee($this->user_info['username']);
        $auth = $e->check_auth($rules);
        $params['auth'] = $auth;

        //检查分配权限
        $fenpei_rules = "PingTaiQueRenFenPei";
        $fenpei_auth = $e->check_auth($fenpei_rules);
        $params['fenpei_auth'] = $fenpei_auth;
        //获取客服
        if ($fenpei_auth) {
            $kefu_list = Employee::get_branch_emp(C('PLATFORM_CONFIRM_SERVER.0'));
            $this->assign('kfs', $kefu_list);
        }
        //获取list
        $aol = new AuOrderList();
        $result = $aol->platform_confirm_list($page, $size, $params);
        // var_export($result);
        $Page = new AjaxPage($result['total'], $size, "get_page");
        $Page->setConfig('theme', " %totalRow% %header% %nowPage%/%totalPage% 页 %first% %upPage% %prePage% %linkPage% %downPage% %nextPage% %end% %jumpform%");
        $show = $Page->show(); // 分页显示输出
        //模板赋值
        $this->assign('params', $params);
        $this->assign('page', $show); // 赋值分页输出
        $this->assign('list', $result['list']);
        $show_from = Channel::get_from();  //获取渠道来源信息
        $this->assign('show_from', $show_from);
        $this->display();
    }

    /**
     * 平台确认处理详情
     */
    public function platform_confirm_detail()
    {
        $order_id = I('get.order_id/d', 0);
        $status = I('get.status/d', 0);
        if ($status > 1) {
            $this->helpJsonResult(500, "平台确认信息错误");
        }
        //检查权限
        $rules = "PingTaiQueRenChaKanSuoYou";
        $e = new Employee($this->user_info['username']);
        $auth = $e->check_auth($rules);
        if ($auth) {
            $order = new AuOrder($order_id);
        } else {
            //判断拍单是否被分配
            $order = $this->is_order_assigned($order_id, 'platform_confirm', true);
        }
        //获取拍单详情
        $detail = $order->platform_confirm_detail();
        $show_from = get_from();  //获取渠道来源信息
        $this->assign('show_from', $show_from);

        //违约流拍
        if ($detail['re_auction_type'] == '2') {
            $this->assign('re_auction_type', '2');
            $this->assign('first_money', $detail['first_money']);
            $this->assign('success_price', $detail['success_price']);
        }

        $scene = new \AuctionCore\AuctionOrder\Scene();
        $scene_detail = $scene->detail($detail['scene_id']);
        $starttime = $scene_detail['starttime'];
        //获取交易服务费
        $row = M('setting')->where(array('name' => 'COMMISION_MIN_FEE'))->find();
        $arr = json_decode($row['remark'], true);
        if ($arr['is_avalible'] == '1') {
            if (date('Y-m-d', strtotime($starttime)) == $arr['startdate']) {
                $min_fee = $arr['commision'];
            } else {
                $min_fee = $row['value'];
            }
        } else {
            $min_fee = $row['value'];
        }
        $min_fee = intval($min_fee);
        $max_fee = M('setting')->where(array('name' => 'COMMISION_MAX_FEE'))->getField('value');
        $max_fee = intval($max_fee);

        $percentage = M('setting')->where(array('name' => 'COMMISION_PERCENTAGE'))->getField('value');
        $percentage = floatval($percentage);
        $this->assign('min_fee', $min_fee);
        $this->assign('max_fee', $max_fee);
        $this->assign('percentage', $percentage);


        //获取平台确认跟踪日志
        $trace_log = $order->get_platform_confirm_trace_log();
        $this->assign('status', $status);
        $this->assign('trace_log', $trace_log);
        $this->assign('rank_data', $detail['rank_data']);
        $this->assign('detail', $detail);
        $this->display();
    }

    /**
     * 平台确认查看详情
     */
    public function platform_confirm_view()
    {
        $order_id = I('get.order_id/d', 0);
        $status = I('get.status/d', 0);
        if ($status < 1) {
            $this->helpJsonResult(500, "平台确认信息错误");
        }
        //检查权限
        $rules = "PingTaiQueRenChaKanSuoYou";
        $e = new Employee($this->user_info['username']);
        $auth = $e->check_auth($rules);
        if ($auth) {
            $order = new AuOrder($order_id);
        } else {
            //判断拍单是否被分配
            $order = $this->is_order_assigned($order_id, 'platform_confirm', true);
        }
        //获取拍单详情
        $detail = $order->platform_confirm_detail();
        $show_from = get_from();  //获取渠道来源信息

        $this->assign('show_from', $show_from);
        //违约流拍
        if ($detail['re_auction_type'] == '2') {
            $this->assign('re_auction_type', '2');
            $this->assign('first_money', $detail['first_money']);
            $this->assign('success_price', $detail['success_price']);
        }
        //获取平台确认跟踪日志
        $trace_log = $order->get_platform_confirm_trace_log();
        $this->assign('status', $status);
        $this->assign('trace_log', $trace_log);
        $this->assign('detail', $detail);
        $this->display();
    }

    /**
     * 平台确认成功
     */
    public function platform_confirm_success()
    {
        $order_id = I('post.order_id/d', 0);
        $owner_id = I('post.owner_id/d', 0);
        $dealer_id = I('post.dealer_id/d', 0);
        $confirm_increase = I('post.fare'); //第一名加价
        $confirm_remark = I('post.confirm_remark');
        //数据验证
        if (!$order_id) {
            $this->helpJsonResult(500, "拍单ID不能为空");
        }
        $order = new AuOrder($order_id);
        $order_detail = $order->detail();
        if (empty($order_detail)) {
            $this->helpJsonResult(500, "未找到拍单信息");
        }
        //找不到车商 建议重拍
        if ($order_detail['bidding_best_price'] == 0 && $order_detail['bid_best_price'] == 0) {
            $this->helpJsonResult(500, '此车辆无车商出价建议确认失败');
        }
        $bidding_best_price = $order_detail['bidding_best_price'] > $order_detail['bid_best_price'] ?
            $order_detail['bidding_best_price'] : $order_detail['bid_best_price'];
        $success_price = $bidding_best_price + $confirm_increase;
        if (!$owner_id) {
            $this->helpJsonResult(500, "车主ID不能为空");
        }
        $car = new \AuctionCore\CarResource\Car($order_detail['car_id']);
        $car_detail = $car->detail();

        //获取场次开始时间
        $scene = new \AuctionCore\AuctionOrder\Scene();
        $scene_detail = $scene->detail($order_detail['scene_id']);
        $starttime = $scene_detail['starttime'];

        $old_order_detail = AuOrder::get_last_order($car_detail['car_id'], $order_id);
        //启动事务
        M()->startTrans();
        //更新拍单状态，记录平台确认加价、自收成交价格
        $order_data = [];
        $order_data['is_consult'] = 1;
        $order_data['platform_confirm_increase'] = $confirm_increase;
        $order_data['success_price'] = $success_price;
        $order_data['commision'] = get_commision($success_price, $starttime);
        $order_data['status'] = 8;
        //更新竞拍最高价或投标最高价
        if ($order_detail['bidding_best_price'] > $order_detail['bid_best_price']) {
            $order_data['bidding_best_price'] = $success_price;
            $success_dealer_id = $order_detail['bidding_best_dealer_id'];
        } else {
            $order_data['bid_best_price'] = $success_price;
            $success_dealer_id = $order_detail['bid_best_dealer_id'];
        }
        //拍单到验车
        $order_data['success_dealer_id'] = $success_dealer_id;
        //车商信息
        $dealer = new Dealer($order_detail['success_dealer_id']);
        $dealer_info = $dealer->detail();
        /**
         * 1、自收人拍到违约重拍车辆确认成功到自收车辆，并把违约重拍车辆标识改为自收车辆标识
         * 2、自收人拍到自收重拍车辆确认成功到自收车辆
         * 3、普通车商拍到重拍车辆或自收重拍车辆确定成功则到待验车
         * 4、自收人或普通车商拍到的违约重拍的车或自收重拍的车则在确认失败时，各自回到违约车辆或自收车辆中
         */
        if ($dealer_info['dealer_type'] == 1) {   //自收人
            $self_receive_car = new \AuctionCore\CarResource\SelfReceiveCar();
            if ($car_detail['is_dealer_breach'] == 1) {        //违约重拍车辆 -- 自收人拍得处理到自收车辆
                $self_receive_car_data = [
                    'car_id' => $order_detail['car_id'],
                    'order_id' => $order_id,
                    'compensate_type' => 3,
                    'self_type' => 4
                ];
                $car_data['is_dealer_breach'] = 0;
                $car_data['is_self_receive'] = 1;       //由违约重拍车辆变为自收车辆
                $car_data['self_receive_dealer_id'] = $success_dealer_id;
                $car_data['self_receive_price'] = $success_price;
                $order_data['fail_type'] = 11;          //失败类型 - 自收人拍得违约重拍车辆
            } elseif ($car_detail['is_self_receive'] == 1) {    //自收重拍车辆 -- 自收人拍的处理到自收车辆
                $self_receive_car_data = [
                    'car_id' => $order_detail['car_id'],
                    'order_id' => $order_id,
                    'compensate_type' => 3,
                    'self_type' => 5
                ];
                $order_data['fail_type'] = 12;
            }
            $self_receive_car_ret = $self_receive_car->add_self_receive_car($self_receive_car_data);
            if (!$self_receive_car_ret) {
                M()->rollback();
                $this->helpJsonResult(500, "添加自收车辆失败");
            }
            $order_data['status'] = 12;
            //平台确认成功到自收车辆后解冻保证金
            AssetCenter::free_all($order_id);
        } else {            //普通车商
            if ($car_detail['is_dealer_breach'] == 1) {          //违约重拍车辆 - 普通车商拍得到待验车
                if ($car_detail['car_source'] == 1) {
                    $order_data['return_check_status'] = 5;
                    if ($car_detail['pay_status'] == 2) {
                        $order_data['first_pay_status'] = 1;
                    }
                } else {
                    $old_price = $old_order_detail['success_price'] + $old_order_detail['company_subsidies'];
                    if ($car_detail['three_in_one'] == 1) {
                        if ($car_detail['pay_status'] > 1) {
                            $order_data['first_pay_status'] = 1;
                        }
                        if ($success_price > $old_price) {
                            $order_data['tail_money'] = $old_order_detail['tail_money'] + ($success_price - $old_price);
                        } else {
                            $order_data['tail_money'] = $old_order_detail['tail_money'];
                        }
                    } else {
                        $order_data['first_pay_status'] = 1;
                        $order_data['tail_money'] = $success_price > $old_price ? $success_price : $old_price;
                    }
                }
            } elseif ($car_detail['is_self_receive'] == 1) {    //自收重拍车辆 - 普通车商拍得到待验车
                if ($car_detail['car_source'] == 1) {
                    $order_data['return_check_status'] = 5;
                    if ($car_detail['pay_status'] == 2) {
                        $order_data['first_pay_status'] = 1;
                    }
                } else {
                    if ($car_detail['three_in_one'] == 1) {
                        if ($car_detail['pay_status'] > 1) {
                            $order_data['first_pay_status'] = 1;
                        }
                    } else {
                        $order_data['first_pay_status'] = 1;
                    }
                }
            }
            //获取车商交付模式：1、先付款后验车 2、先验车后付款
            // $pay_mode = $order->get_dealer_pay_mode();
            // if ($pay_mode['value'] == 2) {
            // $dealer_check_ret = $order->add_car_dealer_check();
            // if (!$dealer_check_ret) {
            //     M()->rollback();
            //     $this->helpJsonResult(500, "操作失败");
            // }
            // $order_data['check_car_status'] = 1;
            // } else {
            $collect_ret = Collection::add(['order_id' => $order_id]);
            if (!$collect_ret) {
                M()->rollback();
                $this->helpJsonResult(500, "操作失败");
            }
            // }
            $order_data['status'] = 8;
        }
        $car_data['success_price'] = $success_price;
        $order_res = $order->update($order_data);
        //更新车源成交价
        $car_res = $car->updateCar($car_data);


        //过户费
        if ($order_detail['transfer_type'] == 1)
            $transfer_fee = 0; //车商自过 没有过户费
        else
            $transfer_fee = $order_detail['transfer_fee'];
        //场次活动
        $res_activity = Scene::is_scene_activity($order_detail['scene_id']);
        if (!empty($res_activity)) {
            //根据场次活动减免规则id找到减免规则
            foreach ($res_activity as $k => $v) {
                if ($v['rules_type'] == 2) { //如果减免规则的rules_type == 2 说明是阶梯立减 去activity_rules表中找到相应的详细规则
                    $activity_reduction = Scene::get_activity_rules_price($v['scene_activity_id'], $success_price);
                } else if ($v['rules_type'] == 1) { //如果减免规则rules_type == 1 说明是活动统一立减,取出scene_activity['amount'] 即可
                    $activity_reduction = $v['amount'];
                }
            }
        } else {
            $activity_reduction = 0; //判断如果没有活动减免价格 则设置scene_activity_amount的值为0;
        }

        $orderFee = [
            'success_price' => $success_price,
            'commision' => $order_detail['commision'],
            'transfer_fee' => $transfer_fee,
            'final_price' => $success_price - $activity_reduction + $order_detail['commision'] + $transfer_fee,
            'activity_reduction' => $activity_reduction
        ];
        $res_fee = $order->addOrderFee($orderFee);

        if (!$order_res || !$car_res || !$res_fee) {
            M()->rollback();
            $this->helpJsonResult(500, '确认失败或已确认,数据未更新');
        }
        M()->commit();

        //第一名加价则插入拍卖出价记录
        if ($confirm_increase > 0) {
            //竞标价大于投标价
            if ($order_detail['bidding_best_price'] > $order_detail['bid_best_price']) {
                $bidding_log_data = array();
                $bidding_log_data['dealer_id'] = $dealer_id;
                $bidding_log_data['order_id'] = $order_id;
                $bidding_log_data['bidding_type'] = 1;
                $bidding_log_data['before_price'] = $bidding_best_price;
                $bidding_log_data['append_price'] = $confirm_increase;
                $bidding_log_data['after_price'] = $success_price;
                $bidding_log_data['createtime'] = date("Y-m-d H:i:s", time());
                $order->add_bidding_log($bidding_log_data);
            } else {
                $bid_log_data = array();
                $bid_log_data['dealer_id'] = $dealer_id;
                $bid_log_data['order_id'] = $order_id;
                $bid_log_data['bid_type'] = 1;
                $bid_log_data['price'] = $success_price;
                $bid_log_data['createtime'] = date("Y-m-d H:i:s", time());
                $order->add_bid_log($bid_log_data);
            }
        }
        //平台确认跟踪日志
        $confirm_trace_log = array(
            'order_id' => $order_id,
            'emp_id' => $this->emp_id,
            'result' => 1,
            'remark' => $confirm_remark,
        );
        $order->add_platform_confirm_trace_log($confirm_trace_log);

        //记录车辆全局跟踪日志
        $log = array(
            'emp_id' => $this->emp_id,
            'order_id' => $order_id,
            'car_id' => $car_detail['car_id'],
            'owner_id' => $owner_id,
            'result' => '平台确认成功'
        );
        \AuctionCore\System\GlobalLog::add($log);

        //记录拍品和车辆跟踪日志
        $this->record_log($order_id, $car_detail['car_id'], $owner_id, "平台确认，成功");

        //自收车商拍得则不发奖券
        if ($dealer_info['dealer_type'] != 1) {
            //发放抽奖卡券
            $Raffle = new \AuctionCore\Other\Raffle();
            $is_raffle = $Raffle->order_binding_card($order_id, 1);
            if ($is_raffle['is_bool'] > 0) {
                $raffle_log = ['emp_id' => $this->emp_id, 'order_id' => $order_id, 'lottery_id' => $is_raffle['cid']];
                $Raffle::grant_lottery_log($raffle_log);
            }

            //发放抽代金券卡券
            $is_coupon = $Raffle->order_binding_card($order_id, 2);
            if ($is_coupon['is_bool'] > 0) {
                $coupon_log = ['emp_id' => $this->emp_id, 'order_id' => $order_id, 'lottery_id' => $is_coupon['cid']];
                $Raffle::grant_lottery_log($coupon_log);
            }
        }
        //输出json格式处理结果
        $this->helpJsonResult(200, "操作成功");
    }

    /**
     * 平台确认继续跟踪
     */
    public function platform_confirm_continue_trace()
    {
        $order_id = I('post.order_id');
        $owner_id = I('post.owner_id');
        $next_trace_time = I('post.next_trace_time');
        $next_trace_time = transform_date($next_trace_time, 2);
        $next_trace_remark = urldecode(I('post.next_trace_remark'));
        //数据验证
        if (!$order_id) {
            $this->helpJsonResult(400, "拍单ID不能为空");
        }
        $order = new AuOrder($order_id);
        $order_detail = $order->detail();
        if (empty($order_detail)) {
            $this->helpJsonResult(400, "未找到拍单信息");
        }
        if (!$owner_id) {
            $this->helpJsonResult(400, "车主ID不能为空");
        }
        if (!$next_trace_time) {
            $this->helpJsonResult(400, "下次跟踪时间不能为空");
        }
        $owner = new \AuctionCore\CarOwner\Owner($owner_id);
        $res1 = $owner->update(
            [
                'next_trace_time' => $next_trace_time
            ]
        );
        if (!$res1) {
            $this->helpJsonResult(400, "更新数据失败,请联系管理员");
        }
        //插入下次跟踪记录
        $platform_confirm_log = [
            'order_id' => $order_id,
            'emp_id' => $this->emp_id,
            'next_trace_time' => $next_trace_time,
            'remark' => urldecode($next_trace_remark),
            'result' => 2
        ];
        $res = $order->add_platform_confirm_trace_log($platform_confirm_log);
        if (!$res) {
            $this->helpJsonResult("跟踪记录失败,请联系管理员");
        }
        //记录拍品和车辆跟踪日志
        $this->record_log($order_id, $order_detail['car_id'], $owner_id, "平台确认，继续跟踪");

        $this->helpJsonResult(200, "操作成功");
    }

    /**
     * 平台确认 - 自收车辆到自收处理/违约重拍车辆到违约车辆
     */
    public function platform_confirm_self_receive_deal()
    {
        //获取外部数据
        $order_id = I('post.order_id/d', 0);
        $owner_id = I('post.owner_id/d', 0);
        $self_receive_deal_remark = urldecode(I('post.remark', '', 'trim'));
        //数据验证
        if (!$order_id) {
            $this->helpJsonResult(400, '拍单ID不能为空');
        }
        $order = new AuOrder($order_id);
        $order_detail = $order->detail();
        if (empty($order_detail)) {
            $this->helpJsonResult(400, "未找到拍单信息");
        }
        if ($order_detail['status'] != 5) {
            $this->helpJsonResult(500, "拍单状态异常,请联系管理员");
        }
        if (!$owner_id) {
            $this->helpJsonResult(400, "车主ID不能为空");
        }
        if (!$self_receive_deal_remark) {
            $this->helpJsonResult(400, '确认失败的备注不能为空');
        }
        //开启事务
        M()->startTrans();
        //添加违约车辆记录
        $car = new Car($order_detail['car_id']);
        $car_detail = $car->detail();
        if ($car_detail['is_dealer_breach'] == 1) {
            $platform_confirm_log = [
                'order_id' => $order_id,
                'emp_id' => $this->emp_id,
                'remark' => urldecode($self_receive_deal_remark),
                'result' => 4
            ];
            $breachCar = new BreachCar($order_detail['car_id']);
            $last_breach_car = $breachCar->detail();
            $breach_car_info = [
                'car_id' => $order_detail['car_id'],
                'compensate_type' => $last_breach_car['compensate_type'],
                'remark' => urldecode($self_receive_deal_remark),
                'issue_id' => $last_breach_car['issue_id'],
                'order_id' => $order_id,
                'breach_type' => 1,
            ];
            $resCar = BreachCar::create($breach_car_info);
            if ($resCar < 1) {
                M()->rollback();
                $this->helpJsonResult(500, "操作失败");
            }
        }
        //如果自收车辆则自收处理到自收车辆中
        if ($car_detail['is_self_receive'] == 1) {
            $platform_confirm_log = [
                'order_id' => $order_id,
                'emp_id' => $this->emp_id,
                'remark' => urldecode($self_receive_deal_remark),
                'result' => 3
            ];
            $self_receive_car = new \AuctionCore\CarResource\SelfReceiveCar();
            $self_receive_car_data = [
                'car_id' => $order_detail['car_id'],
                'order_id' => $order_id,
                'compensate_type' => 3,
                'self_type' => 2
            ];
            $self_receive_car_ret = $self_receive_car->add_self_receive_car($self_receive_car_data);
            if (!$self_receive_car_ret) {
                M()->rollback();
                $this->helpJsonResult(500, "添加自收车辆失败");
            }
        }
        $order_data['fail_type'] = 9;
        $order_data['status'] = 12;
        $order_data['remark_fail'] = $self_receive_deal_remark;
        //更新拍单表数据
        $order_res = $order->update($order_data);
        $platform_confirm_log_res = $order->add_platform_confirm_trace_log($platform_confirm_log);
        if (!$platform_confirm_log_res || !$order_res) {
            M()->rollback();
            $this->helpJsonResult(500, "操作失败或数据已更新未改变");
        }
        //提交事务
        M()->commit();
        //平台确认失败到自收车辆后解冻保证金
        AssetCenter::free_all($order_id);

        //记录拍品和车辆跟踪日志
        $this->record_log($order_id, $order_detail['car_id'], $owner_id, "平台确认，确认失败");

        $this->helpJsonResult(200, "操作成功");
    }


    //分配客服
    public function platFormAssignServer()
    {
        $order_id = I('post.order_id/d', '');
        if (empty($order_id)) {
            $this->helpJsonResult(400, "拍单信息错误!");
        }
        $service_id = I('post.service_id/d', '');
        if (empty($service_id)) {
            $this->helpJsonResult(400, "请选择客服");
        }
        $order = new AuOrder($order_id);
        $order_detail = $order->detail();
        if (empty($order_detail)) {
            $this->helpJsonResult(404, "拍单不存在");
        }
        $data['platform_confirm_service_id'] = $service_id;
        $ok = $order->update($data);
        if (!$ok) {
            $this->helpJsonResult(500, " 分配失败,请稍后再试 ");
        }
        $employee = Employee::user_info_id($service_id);
        /**
         * 记录平台确认日志
         */
        $platform_confirm_log = [
            'order_id' => $order_detail['order_id'],
            'emp_id' => $this->emp_id,
            'remark' => '分配客服为：' . $employee['real_name']
        ];
        $order->add_platform_confirm_trace_log($platform_confirm_log);
        /**
         * 记录车辆、拍品跟踪日志
         */
        $this->record_log($order_detail['order_id'], $order_detail['car_id'], 0, '平台确认，跟踪分配');

        $this->helpJsonResult(200, "分配成功");
    }

    /* --------------平台确认 ending---------------- */


    private function record_log($order_id, $car_id, $owner_id, $action)
    {
        //记录车辆跟踪日志
        \AuctionCore\CarResource\Car::add_car_trace_log($car_id, [
            'action_name' => $action,
            'emp_id' => $this->emp_id
        ]);
        //记录拍品跟踪日志
        \AuctionCore\AuctionOrder\AuOrder::add_order_trace_log($order_id, [
            'action_name' => $action,
            'emp_id' => $this->emp_id
        ]);
        //记录员工操作日志
        \AuctionCore\System\SystemLog::add([
            'emp_id' => $this->emp_id,
            'order_id' => $order_id,
            'car_id' => $car_id,
            'owner_id' => $owner_id,
            'action' => $action
        ]);
    }
}
